<template>
  <div>
    <!-- 三级分类-->
    <Catetory :disableSelect></Catetory>

    <el-card style="margin-top: 10px">
      <div v-show="scene">
        <el-button type="primary" icon="Plus" style="width: 120px" :disabled="!categoryStore.c3Id" @click="addAttr">
          添加属性值
        </el-button>
        <el-table border style="margin-top: 10px" :data="categoryStore.attrList">
          <el-table-column label="序号" type="index" width="80" align="center" />
          <el-table-column label="属性名称" prop="attrName" width="180" />
          <el-table-column label="属性值">
            <template #default="{ row }">
              <el-tag style="margin-left: 5px" v-for="(item, index) in row.attrValueList" :key="item.id">
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template #default="{ row }">
              <el-button type="warning" icon="edit" circle @click="updateAttr(row)"></el-button>
              <el-popconfirm :title="`您确定要删除'${row.attrName}'吗？`" width="260px" icon="Delete" @confirm="deleteAttr(row)">
                <template #reference>
                  <el-button type="danger" icon="delete" circle></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加属性或者编辑属性 -->
      <div v-show="!scene">
        <el-card>
          <el-form style="width: 260px">
            <el-form-item label="属性名称">
              <el-input placeholder="请您输入属性的名字" v-model="attrParams.attrName"></el-input>
            </el-form-item>
          </el-form>
          <el-form :inline="true">
            <el-button
              @click="addAttrValue"
              :disabled="!attrParams.attrName"
              type="primary"
              icon="Plus"
              style="width: 120px"
            >
              添加属性值
            </el-button>
            <el-button @click="cancel" style="width: 60px">取消</el-button>
          </el-form>

          <el-table border stripe style="margin: 10px 0" :data="attrParams.attrValueList">
            <el-table-column label="序号" type="index" width="80" align="center" />
            <el-table-column label="属性值名称">
              <!--row 即为当前属性值对象 -->
              <template #="{ row, $index }">
                <el-input
                  placeholder="请您输入属性值名称"
                  size="default"
                  v-model="row.valueName"
                  :ref="(vc: any) => setInputRef(vc, $index)"
                  :key="$index"
                  v-if="row.editFlag"
                  @blur="toShowMode(row, $index)"
                ></el-input>
                <span v-else @click="toEditMode(row, $index)">{{ row.valueName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="属性值操作" width="220" align="left">
              <template #default="{ row, $index }">
                <el-button type="danger" @click="delAttrValue($index)" icon="delete" circle></el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-form :inline="true">
            <el-button
              @click="saveAttr"
              type="primary"
              icon="Plus"
              style="width: 80px"
              :disabled="attrParams.attrValueList.length <= 0"
            >
              保存
            </el-button>
            <el-button @click="cancel" type="primary" style="width: 60px">取消</el-button>
          </el-form>
        </el-card>
      </div>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import Catetory from '@/components/Category/Catetory.vue'
import { useCategoryStore } from '@/stores/modules/category'
import { watch, ref, reactive, nextTick } from 'vue'
import type { Attr, AttrValue } from '@/api/product/attr/type'
import { reqDeleteAttr, reqSaveAttr } from '@/api/product/attr'
import { ElMessage } from 'element-plus'

const categoryStore = useCategoryStore()

const scene = ref(true)
// 禁用分类选择
const disableSelect = ref(false)

// 添加属性按钮回调
const addAttr = () => {
  scene.value = false
  disableSelect.value = true

  // 每次点击的时候，先清空一下数据，再收集数据
  Object.assign(attrParams, {
    // 属性id
    id: '',
    // 属性名称
    attrName: '',
    // 属性值列表
    attrValueList: [],
    // 3级分类id
    categoryId: categoryStore.c3Id,
    // 给3级分类添加属性
    catetoryLevel: 3,
  })
}

// 准备一个数据存储 el-input 组件
const inputCompArr = ref<any>([])

const setInputRef = (element: any, $index: number) => {
  inputCompArr.value[$index] = element
}

// // 处理input组件变化的回调
// const handleInputComp = (vc:any, $index: number) => {
//   console.log("vxcvc")
//   console.log(vc)
//   console.log($index)
// }

// 修改属性
const updateAttr = (row:Attr) => {
  scene.value = false
  disableSelect.value = true

  // // 收集3级分类id
  // attrParams.categoryId = categoryStore.c3Id
  // // 收集属性id

  // 把row的属性值拷贝给attrParams，注意这里需要使用深拷贝
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

// 删除属性回调
const  deleteAttr = (row: Attr) => { 
  reqDeleteAttr(row.id as number).then((resp) => {
    if (resp.code === 200) {
      ElMessage.success({
        message: '删除成功',
      })
      // 删除成功后，重新请求属性列表
      categoryStore.reqAttrList()
      return

    } else {
      ElMessage.error({
        message: resp.msg,
      })
      return;
    }
  })
}


// 删除属性值回调
const delAttrValue = ($index: number) => {
  attrParams.attrValueList.splice($index, 1)
  inputCompArr.value.splice($index, 1)
}

// 添加属性值按钮回调
const addAttrValue = () => {
  console.log('添加属性值')

  attrParams.attrValueList.push({
    valueName: '',
    id: '',
    attrId: '',
    editFlag: true,
  })

  // 最后一个el-input 组件自动聚焦
  nextTick(() => {
    let lastInput = inputCompArr.value[inputCompArr.value.length - 1]
    if (lastInput) {
      lastInput.focus()
    }
  })
}

// 属性值切换到查看模式
const toShowMode = (row: AttrValue, $index: number) => {
  // 如果没有输入属性值，则提示用户输入属性值名称
  if (!row.valueName.trim()) {
    ElMessage.error({
      message: '请输入属性值名称',
    })
    // 删除属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    return
  }

  // 属性值名称重复判断
  let repeate = attrParams.attrValueList.find((item) => {
    // 把自己排除
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (repeate) {
    ElMessage.error({
      message: '属性值名称重复',
    })
    // 删除属性值重复的
    attrParams.attrValueList.splice($index, 1)
    return
  }

  // 转换到 查看模式
  row.editFlag = false
}

// 属性值切换到编辑模式
const toEditMode = (row: AttrValue, $index: number) => {
  // 转换到 编辑模式
  row.editFlag = true

  nextTick(() => {
    // 聚焦 el-input
    let currentInput = inputCompArr.value[$index]
    if (currentInput) {
      currentInput.focus()
    }
  })
}

// 保存按钮回调函数
const saveAttr = () => {
  console.log('保存属性')
  // 发起请求
  reqSaveAttr(attrParams).then((data) => {
    if (data.code === 200) {
      ElMessage.success({
        message: '保存成功',
      })
      scene.value = true
      // 保存成功后，重新请求属性列表
      categoryStore.reqAttrList()
    } else {
      ElMessage.error({
        message: data.msg,
      })
      return
    }
  })
}

// 取消按钮回调函数
const cancel = () => {
  scene.value = true
  disableSelect.value = false
}

// 收集新增属性值
let attrParams = reactive<Attr>({
  // 属性id
  id: '',
  // 属性名称
  attrName: '',
  // 属性值列表
  attrValueList: [],
  // 3级分类id
  categoryId: '',
  // 给3级分类添加属性
  catetoryLevel: 3,
})

// 监听3级分类id的改变，如果改变请求属性列表
watch(
  () => categoryStore.c3Id,
  (newVal, _) => {
    // 监听到分类3改变，先清空属性列表
    categoryStore.attrList = []
    if (newVal) {
      // 如果分类3有值，请求属性列表
      categoryStore.reqAttrList()
    }
  },
)
</script>

<style lang="scss" scoped></style>
